package com.wsfk.ssm.service.client;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import maps.com.wsfk.ssm.client.ClientMapper;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.wsfk.ssm.entity.BookInfo;
import com.wsfk.ssm.entity.HandBook;
import com.wsfk.ssm.entity.User;
import com.wsfk.ssm.messages.CodeMessage;
import com.wsfk.ssm.messages.HandBookMessage;
import com.wsfk.ssm.messages.LoginMessage;
import com.wsfk.ssm.messages.Message;
import com.wsfk.ssm.messages.RegistMessage;
import com.wsfk.ssm.messages.UpdateMessage;
import com.wsfk.ssm.path.CallPath;
import com.wsfk.ssm.path.SiteUtil;
import com.wsfk.ssm.service.FileSvc;
import com.wsfk.ssm.tools.DownloadNumUtil;
import com.wsfk.ssm.tools.QRCodeUtil;

/**
 * 
 * @author zhangbao
 *
 */
@Service("ClientSvcImpl")
public class ClientSvcImpl implements ClientSvc {
	Logger log = Logger.getLogger(this.getClass());
	
	private ClientMapper clientMapper;

	private FileSvc fileSvc;
	
	@Resource
	public void setFileSvc(FileSvc fileSvc) {
		this.fileSvc = fileSvc;
	}

	@Resource
	public void setClientMapper(ClientMapper clientMapper) {
		this.clientMapper = clientMapper;
	}

	//免费版下载码下载接口
	public HandBookMessage queryBooksByDownNum(String downnum) {
		
		List<BookInfo> books =clientMapper.queryHandBookByDownloadNum(downnum);
		HandBookMessage message =new HandBookMessage();
		if(books.size()<=0){
			message.setStatus("failure");
			message.setError("没有找到该手册");
		}else{
			BookInfo book =books.get(0);
			Date stopDate = book.getStopDate();
			if(stopDate.compareTo(new Date())==1){
				//手册未过期
				message.setStatus("success");
				message.setError("");
				message.setBook(books.get(0));
			}else{
				//手册已过期
				message.setStatus("failure");
				message.setError("该手册已过期，不能下载！");
			}
			
		}
		return message;
	}


	//注册接口
	public RegistMessage addUser(User user) {
		RegistMessage message =new RegistMessage();
		user.setId(UUID.randomUUID().toString());
		user.setStatus(User.ACTIVITY);
		if(isHasUserName(user.getUserName())){
			message.setStatus("failure");
			message.setError("用户名已存在");
			return message;
		}
		int n =clientMapper.addUser(user);
		if(n>0){
			message.setStatus("success");
			//注册成功向数据中添加handbook三条记录
			insert3books(user);
			List<BookInfo> infos =clientMapper.queryBookInfos(user.getUserName(),user.getPassword());
			message.setBooks(infos);
		}else{
			message.setStatus("failure");
			message.setError("注册失败，请重新注册");
		}
		return message;
	}

	//登录接口
	public LoginMessage queryUserByUserNameAndPwd(String userName, String pwd) {
		LoginMessage message =new LoginMessage();
		User user =clientMapper.queryUserByUserNameAndPwd(userName.toLowerCase(), pwd);
		if(user!=null){
			message.setStatus("success");
			message.setCompany(user.getCompany());
		}else{
			message.setStatus("failure");
			message.setError("用户名或密码错误");
		}
		return message;
	}


	//验证用户名是否存在
	public boolean isHasUserName(String userName) {
		return clientMapper.queryUserByUserName(userName)>0;
	}

	//添加3本手册
	public void insert3books(User user){
		for (int i = 0; i < 3; i++) {
			addBook(user.getId());
		}
	}
	/**
	 * 内购    添加一本手册
	 * @param userid
	 * @return
	 */
	public int addBook(String userid) {
		HandBook book =HandBook.creatNewBook(randomDownnum(), userid);
		book.setId(UUID.randomUUID().toString());
		int i  = clientMapper.insertBooks(book);
		return i;
	}

	//更新手册列表接口
	public List<BookInfo> queryBookInfos(String userName,String pwd) {
		return clientMapper.queryBookInfos(userName,pwd);
	}


	//单个更新手册接口  该接口暂时没有用到
	public UpdateMessage queryBookInfo(String userName, String pwd, String version,
			String downnum) {
		UpdateMessage um =new UpdateMessage();
		BookInfo book =clientMapper.queryBookInfo(userName, pwd, version, downnum);
		if(book !=null){
			um.setStatus("success");
			um.setBook(book);
		}else{
			um.setStatus("failure");
			um.setError("当前版本不一致，请刷新列表后再进行更新！");
		}
		return um;
	}


	//发布审核接口
	public UpdateMessage updatePublishState(String userName, String pwd, String downnum,
			String publishState) {
		UpdateMessage um =new UpdateMessage();
		Map<String, Object> param =new HashMap<String, Object>();
		param.put("userName", userName);
		param.put("pwd", pwd);
		param.put("publishState", publishState);
		param.put("downnum", downnum);
		
		Date nowDate =new Date();
		Calendar cr =Calendar.getInstance();
		cr.setTime(nowDate);
		cr.add(Calendar.MONTH, 6);
		Date stopDate =cr.getTime();//加6个月后的时间
		param.put("publishDate", nowDate);
		param.put("stopDate", stopDate);
		
		int n =clientMapper.updatePublishState(param);
		if (n>0) {
			//查询手册信息
			BookInfo book =clientMapper.queryBookInfoDownnum(userName, pwd, downnum);
			
			/*//生成二维码
			CodeMessage cm =new CodeMessage(downnum);
			String dir ="/"+userName+"/towCodes/"+nowDate.getTime()+".png";
			String path =SiteUtil.querySite();
			QRCodeUtil.createQRcode(path+dir, cm);
			String savePath =path.substring(path.lastIndexOf("/")+1, path.length());*/
			
			User user = new User();
			user.setUserName(userName);
			HandBook hand = new HandBook();
			hand.setId(book.getId());
			String savePath = new CallPath().codeWay(user, hand).build();
			
			fileSvc.saveTowCodes(user, hand, downnum) ;
			
			clientMapper.updateTowCodePath(userName, pwd, savePath, downnum);
			
		 	
		 	
		 	
		 	
			if(HandBook.PUBLISH.equalsIgnoreCase(book.getPublishState())){
				book.setTowCode(savePath);//发布之后将下载码地址添加上去
				um.setBook(book);
				um.setStatus("success");
			}
		}else{
			um.setStatus("failure");
			um.setError("发布失败，请重新发布");
		}
		return um;
	}

	public Message updatePwd(String userName, String pwd, String newPwd) {
		Message msg = new Message();
		int i = clientMapper.updatePwd(userName, pwd, newPwd);
		if(i==1){
			msg.setStatus("success");
		}else{
			msg.setStatus("failure");
			msg.setError("旧密码有误，请重新输入！");
		}
		return msg;
	}
	
	
	/**
	 * 这个方法是用来生成下载码的
	 * @return
	 */
	public String randomDownnum(){
		String downnum = DownloadNumUtil.random(8);
		while(clientMapper.queryCountsOfDownnum(downnum)>0){
			downnum = DownloadNumUtil.random(8);
		}
		return downnum;
	}
	
	/**
	 * 内购    续费
	 * @return
	 */
	public int updateEndTime(String bookid) {
		HandBook book = clientMapper.queryBookById(bookid);
		if(book==null){
			log.error("not find handBook "+bookid);
			throw new RuntimeException("not find handBook");
		}
		book.renewal();
		int i = clientMapper.updateBook(book);
		
		if(i==0){
			log.error("No modification success "+bookid);
			throw new RuntimeException("No modification success");
		}
		
		return i;
	}

	/**
	 * 修改手册发布状态，添加二维码，生成二维码
	 */
	public UpdateMessage updatePublishState(){
		return null;
	}
	

}
